package com.crm.api.controller;

import com.crm.api.common.Result;
import com.crm.api.entity.Employee;
import com.crm.api.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 员工控制器
 */
@Slf4j
@RestController
@RequestMapping("/employees")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 获取员工列表
     */
    @GetMapping
    public Result<Map<String, Object>> getEmployees(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String realName,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String department,
            @RequestParam(required = false) String position,
            @RequestParam(required = false) String role,
            @RequestParam(required = false) Boolean isActive) {
        
        log.info("获取员工列表: page={}, size={}, realName={}, department={}", 
                page, size, realName, department);
        
        Map<String, Object> result = employeeService.getEmployees(
                page, size, realName, username, department, position, role, isActive);
        
        return Result.success(result);
    }

    /**
     * 获取员工详情
     */
    @GetMapping("/{id}")
    public Result<Employee> getEmployee(@PathVariable Integer id) {
        log.info("获取员工详情: id={}", id);
        
        Employee employee = employeeService.getEmployeeById(id);
        if (employee == null) {
            return Result.error(404, "员工不存在");
        }
        
        // 出于安全考虑，不返回密码
        employee.setPassword(null);
        
        return Result.success(employee);
    }

    /**
     * 创建员工
     */
    @PostMapping
    public Result<Employee> createEmployee(@Valid @RequestBody Employee employee) {
        // 获取当前用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        
        log.info("创建员工: realName={}, username={}, creator={}", 
                employee.getRealName(), employee.getUsername(), username);
        
        // 检查用户名是否已存在
        if (employeeService.existsByUsername(employee.getUsername())) {
            return Result.error(400, "用户名已存在");
        }
        
        // 检查员工编号是否已存在
        if (employee.getEmployeeCode() != null && 
            employeeService.existsByEmployeeCode(employee.getEmployeeCode())) {
            return Result.error(400, "员工编号已存在");
        }
        
        Employee createdEmployee = employeeService.createEmployee(employee);
        // 出于安全考虑，不返回密码
        createdEmployee.setPassword(null);
        
        return Result.success(createdEmployee);
    }

    /**
     * 更新员工
     */
    @PutMapping("/{id}")
    public Result<Employee> updateEmployee(@PathVariable Integer id, @Valid @RequestBody Employee employee) {
        log.info("更新员工: id={}, realName={}", id, employee.getRealName());
        
        employee.setId(id);
        
        // 检查用户名是否已被其他记录使用
        if (employeeService.existsByUsernameAndNotId(employee.getUsername(), id)) {
            return Result.error(400, "用户名已存在");
        }
        
        // 检查员工编号是否已被其他记录使用
        if (employee.getEmployeeCode() != null && 
            employeeService.existsByEmployeeCodeAndNotId(employee.getEmployeeCode(), id)) {
            return Result.error(400, "员工编号已存在");
        }
        
        Employee updatedEmployee = employeeService.updateEmployee(employee);
        if (updatedEmployee == null) {
            return Result.error(404, "员工不存在");
        }
        
        // 出于安全考虑，不返回密码
        updatedEmployee.setPassword(null);
        
        return Result.success(updatedEmployee);
    }

    /**
     * 删除员工
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteEmployee(@PathVariable Integer id) {
        log.info("删除员工: id={}", id);
        
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUsername = authentication.getName();
        Employee currentEmployee = employeeService.getEmployeeByUsername(currentUsername);
        
        // 不能删除自己
        if (currentEmployee.getId().equals(id)) {
            return Result.error(400, "不能删除自己的账号");
        }
        
        // 检查是否有关联的业务
        if (employeeService.hasRelatedBusinesses(id)) {
            return Result.error(400, "该员工下还有关联的业务，无法删除");
        }
        
        // 检查是否有关联的工单
        if (employeeService.hasRelatedWorkOrders(id)) {
            return Result.error(400, "该员工下还有关联的工单，无法删除");
        }
        
        boolean deleted = employeeService.deleteEmployee(id);
        if (!deleted) {
            return Result.error(404, "员工不存在");
        }
        
        return Result.success();
    }

    /**
     * 重置员工密码
     */
    @PostMapping("/{id}/reset-password")
    public Result<Void> resetEmployeePassword(@PathVariable Integer id, @RequestBody Map<String, String> request) {
        String password = request.get("password");
        log.info("重置员工密码: id={}", id);
        
        if (password == null || password.trim().isEmpty()) {
            return Result.error(400, "密码不能为空");
        }
        
        if (password.length() < 6) {
            return Result.error(400, "密码长度不能少于6位");
        }
        
        boolean updated = employeeService.resetPassword(id, password);
        if (!updated) {
            return Result.error(404, "员工不存在");
        }
        
        return Result.success();
    }

    /**
     * 启用/禁用员工
     */
    @PatchMapping("/{id}/status")
    public Result<Void> toggleEmployeeStatus(@PathVariable Integer id, @RequestBody Map<String, Boolean> request) {
        Boolean isActive = request.get("isActive");
        log.info("切换员工状态: id={}, isActive={}", id, isActive);
        
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUsername = authentication.getName();
        Employee currentEmployee = employeeService.getEmployeeByUsername(currentUsername);
        
        // 不能禁用自己
        if (currentEmployee.getId().equals(id) && !isActive) {
            return Result.error(400, "不能禁用自己的账号");
        }
        
        boolean updated = employeeService.updateEmployeeStatus(id, isActive);
        if (!updated) {
            return Result.error(404, "员工不存在");
        }
        
        return Result.success();
    }

    /**
     * 获取部门列表
     */
    @GetMapping("/departments")
    public Result<List<String>> getDepartments() {
        log.info("获取部门列表");
        
        List<String> departments = employeeService.getDepartments();
        return Result.success(departments);
    }

    /**
     * 获取职位列表
     */
    @GetMapping("/positions")
    public Result<List<String>> getPositions() {
        log.info("获取职位列表");
        
        List<String> positions = employeeService.getPositions();
        return Result.success(positions);
    }
}